﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MIC_GUI.Misc;


namespace MIC_GUI.Model
{
    /// <summary>
    /// Object for adding new data to a Graph
    /// When adding new data to this object, the Graph UserControl, that it is associated with,
    /// will automatically be updated with the new value through bindings and Dependcy properties
    /// </summary>
    public class SerialDataValue
    {
        #region fields

        private ThreadSafeObservableCollection<DataItem> dataValues = null;
        private Int32 SamplesWindowSize = 50;
        private long currentSampleCounter = 0;
        private DateTime lastTime = DateTime.Now;

        #endregion

        #region Ctor
        /// <summary>
        /// Constructor
        /// </summary>
        public SerialDataValue()
        {
            dataValues = new ThreadSafeObservableCollection<DataItem>();
            SamplesWindowSize = MIC_GUI.Properties.Settings.Default.SAMPLE_WINDOW_SIZE;

        }
        #endregion

        #region methods

        /// <summary>
        /// Adds a new value to a Graph
        /// </summary>
        /// <param name="value">Value to be added</param>
        public void Add(double value)
        {
            DateTime now = DateTime.Now;
            
            //makes a new item based on the values
            DataItem dataItem = new DataItem
            {
                DataValue = value,
                TimeSampled = now.Subtract(lastTime),
                SampleSequenceNumber = currentSampleCounter++
            };

                try
                {
                    dataValues.Add(dataItem);

                    while (dataValues.Count >= SamplesWindowSize)
                        dataValues.RemoveAt(0);

                }
                catch (Exception ex)
                {
                    string text = ex.Message;
                }

            
            lastTime = now;
        }
        
        #endregion

        #region properties

        /// <summary>
        /// Thread safe container filled with Graph Data Items
        /// </summary>
        public ThreadSafeObservableCollection<DataItem> DataValues
        {
            get { return dataValues; }
            set { dataValues = value; }
        }
        #endregion

    }
}
